//
//  CommonUtil.m
//  ProjectTemplet
//
//  Created by HouKavin on 16/2/4.
//  Copyright © 2016年 HouKavin. All rights reserved.
//


//这下面七个引用或宏都是为了获取IP服务的
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"


#import "CommonUtil.h"


@implementation CommonUtil

//提示信息(alertView)
+(void)showAlert:(NSString*) msg{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];//显示提示框
    
}

//展示loading
+(void)showLoadingWithMessage:(NSString *)message{
    CoreSVPLoading(message, YES);
}

//loading消失
+(void)dismissLoading{
    [CoreSVP dismiss];
}

//提示信息居中
+(void)showMessageInCenter:(NSString *)message{
    [CoreSVP showSVPWithType:CoreSVPTypeCenterMsg Msg:message duration:1.5 allowEdit:YES beginBlock:nil completeBlock:nil];
}

//底部提示信息
+(void)showMessageInBottom:(NSString *)message{
    [CoreSVP showSVPWithType:CoreSVPTypeBottomMsg Msg:message duration:1.5 allowEdit:YES beginBlock:nil completeBlock:nil];
}

//成功提示信息
+(void)showSuccessMessage:(NSString *)message{
    CoreSVPSuccess(message)
}

//失败提示信息
+(void)showErrorMessage:(NSString *)message{
    CoreSVPError(message)
}

//进度条加载框
+(void)showProgess:(CGFloat)progress withMessage:message{
    //SVProgressHUDMaskTypeNone 允许用户交互
    [CoreSVP showProgess:progress Msg:message maskType:SVProgressHUDMaskTypeClear];
}

#pragma mark - FOr version

+(BOOL)isLesserThanOrEqual:(NSString *)ver {
    
    NSString *osVersion = [[UIDevice currentDevice] systemVersion];
    if ([osVersion compare:ver options:NSNumericSearch] != NSOrderedAscending) {
        return YES;
    }
    
    return NO;
}

// infoDictionary 包含了项目中几乎所有的基本信息，SDK版本，项目名称等
+(NSString*) getBundleString :(NSString*) key{
    NSString *str = [[[NSBundle mainBundle] infoDictionary] objectForKey:key];
    if(str==nil)
        str=@"";
    return str;
}

//获取程序唯一标识符
+(NSString *)getIdentifierName{
    return [[NSBundle mainBundle] bundleIdentifier];
}

//获取程序的版本号
+(NSString *)getBundleVersionValue{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}

//获取uuid的值
+(NSString *)getUUIDValue{
    return [UIDevice currentDevice].identifierForVendor.UUIDString;
}

//获取当前设备的IPv4或IPv6格式的IP[IPhoneIP getIPAddress:YES];会获取网关ip
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
    @[ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}

//获取当前设备所有的ip值，以字典形式展示
+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}


@end
